<script setup lang="tsx">
import { ref, watch } from 'vue';
import { ElTag } from 'element-plus';
import { $t } from '@/locales';
import UserSearch from '@/views/system/user/modules/user-search.vue';
import { useTable } from '@/hooks/common/table';
import { fetchGetUserInfoByPage, fetchSaveUserDeptBatch } from '@/service/api';
import { useLoading } from '~/packages/hooks';

defineOptions({ name: 'UserSelectDialog' });

interface Props {
  deptId: CommonType.IdType;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

// 关闭对话框
function closeDialog() {
  visible.value = false;
}

const {
  columns,
  // columnChecks,
  data,
  // getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetUserInfoByPage,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    condition: {}
  },
  columns: () => [
    { type: 'selection', width: 48 },
    { prop: 'index', label: $t('common.index'), width: 64 },
    { prop: 'username', label: '用户名', minWidth: 200, align: 'left' },
    { prop: 'nickname', label: '用户昵称', minWidth: 200, align: 'left' },
    { prop: 'fullname', label: '姓名', minWidth: 200, align: 'left' },
    { prop: 'sexText', label: '性别', minWidth: 200, align: 'left' },
    { prop: 'mobile', label: '手机号码', minWidth: 200, align: 'left' },
    { prop: 'deptText', label: '所在部门', minWidth: 200, align: 'left' },
    { prop: 'postText', label: '用户岗位', minWidth: 200, align: 'left' },
    {
      prop: 'enabled',
      label: $t('form.enabled'),
      width: 100,
      align: 'center',
      formatter: row => (
        <ElTag type={row.enabled === 1 ? 'success' : 'danger'}>
          {row.enabled === 1 ? $t('form.enabledOptions.enabled') : $t('form.enabledOptions.disabled')}
        </ElTag>
      )
    },
    { prop: 'createTime', label: $t('common.createTime'), minWidth: 200, align: 'left' }
  ]
});

const checkedRowKeys = ref<Api.System.User.UserInfoRecord[]>();

const { loading: handleLoading, startLoading, endLoading } = useLoading();

// 确认选择
async function handleSubmit() {
  try {
    startLoading();
    const { error } = await fetchSaveUserDeptBatch({
      deptId: props.deptId,
      userList: checkedRowKeys.value
    });
    if (error) return;
    window.$message?.success($t('common.operateSuccess'));
    closeDialog();
    emit('submitted');
  } finally {
    endLoading();
  }
}

watch(
  () => visible.value,
  () => {
    if (visible.value) {
      getDataByPage();
    }
  }
);
</script>

<template>
  <ElDialog v-model="visible" title="选择用户" width="1000" :close-on-click-modal="false">
    <ElContainer v-loading="handleLoading">
      <ElHeader>
        <ElCard class="card-wrapper" :body-style="{ paddingTop: 0, paddingBottom: 0 }">
          <UserSearch v-model="searchParams.condition" @reset="resetSearchParams" @search="getDataByPage" />
        </ElCard>
      </ElHeader>
      <ElMain>
        <ElCard class="h-full sm:flex-1-hidden card-wrapper">
          <template #header>
            <div class="flex flex-wrap items-center justify-between gap-5">
              <p>用户列表</p>
            </div>
          </template>
          <div class="h-[calc(100%-45px)]">
            <ElTable
              v-loading="loading"
              height="100%"
              border
              class="sm:h-full"
              :data="data"
              row-key="id"
              show-overflow-tooltip
              @selection-change="checkedRowKeys = $event"
            >
              <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
            </ElTable>
          </div>
          <div class="mt15px flex justify-end">
            <ElPagination
              v-if="mobilePagination.total"
              background
              layout="total,prev,pager,next,sizes"
              v-bind="mobilePagination"
              @current-change="mobilePagination['current-change']"
              @size-change="mobilePagination['size-change']"
            />
          </div>
        </ElCard>
      </ElMain>
    </ElContainer>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDialog">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.el-container {
  height: 600px;

  .el-header {
    height: fit-content;
  }
}
</style>
